<template>
    <div class="pets-data-analysis">
        <el-card>
            <h4>宠物数据分析</h4>
        </el-card>
        <!-- 两个饼图在同一行 -->
        <div class="chart-row">
            <el-card class="chart-card">
                <h5>性别分布</h5>
                <div ref="chartGender" class="chart-container" style="height: 200px"></div>
            </el-card>
            <el-card class="chart-card">
                <h5>品种分布</h5>
                <div ref="chartSpecies" class="chart-container" style="height: 200px"></div>
            </el-card>
        </div>
        <!-- 三个柱状图 -->
        <div class="chart-row">
            <el-card class="chart-card-3">
                <h5>宠物发布来源</h5>
                <div ref="chartPublishType" class="chart-container" style="height: 200px"></div>
            </el-card>
            <el-card class="chart-card-4">
                <h5>地区分布</h5>
                <div ref="chartRegion" class="chart-container" style="height: 200px"></div>
            </el-card>
            <el-card class="chart-card-5">
                <h5>宠物年龄分布</h5>
                <div ref="chartAge" class="chart-container" style="height: 200px"></div>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import * as echarts from "echarts";
import { getPetAnalysisAPI } from "@/api/pet";

// 所有宠物数据
const PetData = ref([]);
const gerderData = ref([]); // 性别数据
const publishTypeData = ref([]); // 发布类型
const speciesData = ref([]); // 品种
const regionData = ref([]); // 地区
const ageData = ref([]); // 年龄分布

// 图表实例
const chartGender = ref(null);
const chartPublishType = ref(null);
const chartSpecies = ref(null);
const chartRegion = ref(null);
const chartAge = ref(null);

// 获取宠物分析数据
const getPetAnalysis = async () => {
    try {
        const res = await getPetAnalysisAPI();
        PetData.value = res;
        gerderData.value = res.gender;
        publishTypeData.value = res.publishType;
        speciesData.value = res.species;
        regionData.value = res.region;
        ageData.value = res.age;
    } catch (error) {
        console.error("获取宠物分析数据失败:", error);
    }
};

// 初始化性别分布图表
const initGenderChart = () => {
    if (!chartGender.value) return;

    // 销毁旧实例防止内存泄漏
    if (chartGender.value.chart) {
        chartGender.value.chart.dispose();
    }
    chartGender.value.chart = echarts.init(chartGender.value);
    const option = {
        tooltip: {
            trigger: "item",
            formatter: "{b}: {c} ({d}%)",
        },
        legend: {
            orient: "horizontal",
            bottom: "5%",
            left: "center",
            data: ["男", "女"],
        },
        series: [
            {
                name: "性别分布",
                type: "pie",
                radius: ["40%", "70%"],
                avoidLabelOverlap: false,
                label: {
                    show: true,
                    position: "outside",
                    formatter: "{b}: {d}%",
                },
                labelLine: {
                    show: true,
                },
                data: [],
            },
        ],
    };

    // 设置图表选项
    chartGender.value.chart.setOption(option);

    // 监听窗口大小变化，调整图表
    window.addEventListener("resize", () => {
        if (chartGender.value.chart) {
            chartGender.value.chart.resize();
        }
    });
};

// 更新性别分布图表数据
const updateGenderChart = () => {
    if (!chartGender.value || !chartGender.value.chart || !gerderData.value.length) return;

    // 转换数据格式
    const formattedData = gerderData.value.map((item) => ({
        value: item.count,
        name: item.gender,
    }));

    // 更新图表数据
    chartGender.value.chart.setOption({
        series: [
            {
                data: formattedData,
            },
        ],
    });
};

// 初始化发布来源表格
const initPublishTypeChart = () => {
    if (!chartPublishType.value) return;

    // 销毁旧实例防止内存泄漏
    if (chartPublishType.value.chart) {
        chartPublishType.value.chart.dispose();
    }
    chartPublishType.value.chart = echarts.init(chartPublishType.value);

    const option = {
        tooltip: {
            trigger: "item",
        },
        grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true,
        },
        xAxis: {
            type: "category",
            data: [],
        },
        yAxis: {
            type: "value",
        },
        series: [
            {
                name: "数量",
                type: "bar",
                data: [],
            },
        ],
    };

    // 设置图表选项
    chartPublishType.value.chart.setOption(option);

    // 监听窗口大小变化，调整图表
    window.addEventListener("resize", () => {
        if (chartPublishType.value.chart) {
            chartPublishType.value.chart.resize();
        }
    });
};

// 更新发布来源表格数据
const updatePublishTypeChart = () => {
    if (!chartPublishType.value || !chartPublishType.value.chart || !publishTypeData.value.length) return;

    // 转换数据格式
    const xData = publishTypeData.value.map((item) => item.publishType);
    const yData = publishTypeData.value.map((item) => item.count);

    // 更新图表数据
    chartPublishType.value.chart.setOption({
        xAxis: {
            data: xData,
        },
        series: [
            {
                data: yData,
            },
        ],
    });
};

// 初始化品种分布表格
const initSpeciesChart = () => {
    if (!chartSpecies.value) return;

    // 销毁旧实例防止内存泄漏
    if (chartSpecies.value.chart) {
        chartSpecies.value.chart.dispose();
    }
    chartSpecies.value.chart = echarts.init(chartSpecies.value);

    const option = {
        tooltip: {
            trigger: "item",
            formatter: "{b}: {c} ({d}%)",
        },
        legend: {
            orient: "horizontal",
            bottom: "5%",
            left: "center",
            data: [],
        },
        series: [
            {
                name: "品种分布",
                type: "pie",
                radius: ["40%", "70%"],
                avoidLabelOverlap: false,
                label: {
                    show: true,
                    position: "outside",
                    formatter: "{b}: {d}%",
                },
                labelLine: {
                    show: true,
                },
                data: [],
            },
        ],
    };

    // 设置图表选项
    chartSpecies.value.chart.setOption(option);

    // 监听窗口大小变化，调整图表
    window.addEventListener("resize", () => {
        if (chartSpecies.value.chart) {
            chartSpecies.value.chart.resize();
        }
    });
};

// 更新品种分布表格数据
const updateSpeciesChart = () => {
    if (!chartSpecies.value || !chartSpecies.value.chart || !speciesData.value.length) return;

    // 转换数据格式
    const formattedData = speciesData.value.map((item) => ({
        value: item.count,
        name: item.species,
    }));

    // 更新图表数据
    chartSpecies.value.chart.setOption({
        legend: {
            data: formattedData.map((item) => item.name),
        },
        series: [
            {
                data: formattedData,
            },
        ],
    });
};

// 初始化地区分布柱状图
const initRegionChart = () => {
    if (!chartRegion.value) return;

    // 销毁旧实例防止内存泄漏
    if (chartRegion.value.chart) {
        chartRegion.value.chart.dispose();
    }
    chartRegion.value.chart = echarts.init(chartRegion.value);

    const option = {
        tooltip: {
            trigger: "item",
            formatter: "{b}: {c}",
        },
        grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true,
        },
        xAxis: {
            type: "category",
            data: [],
        },
        yAxis: {
            type: "value",
        },
        series: [
            {
                name: "地区分布",
                type: "bar",
                data: [],
            },
        ],
    };

    // 设置图表选项
    chartRegion.value.chart.setOption(option);

    // 监听窗口大小变化，调整图表
    window.addEventListener("resize", () => {
        if (chartRegion.value.chart) {
            chartRegion.value.chart.resize();
        }
    });
};

// 更新地区分布柱状图数据
const updateRegionChart = () => {
    if (!chartRegion.value || !chartRegion.value.chart || !regionData.value.length) return;

    // 转换数据格式
    const xData = regionData.value.map((item) => item.region);
    const yData = regionData.value.map((item) => item.count);

    // 更新图表数据
    chartRegion.value.chart.setOption({
        xAxis: {
            data: xData,
        },
        series: [
            {
                data: yData,
            },
        ],
    });
};

// 初始化宠物年龄分布条形图
const initAgeChart = () => {
    if (!chartAge.value) return;

    // 销毁旧实例防止内存泄漏
    if (chartAge.value.chart) {
        chartAge.value.chart.dispose();
    }
    chartAge.value.chart = echarts.init(chartAge.value);

    const option = {
        tooltip: {
            trigger: "item",
            formatter: "{b}: {c}只",
        },
        grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true,
        },
        xAxis: {
            type: "category",
            data: [],
        },
        yAxis: {
            type: "value",
            name: "宠物数量",
        },
        series: [
            {
                name: "宠物年龄分布",
                type: "bar",
                data: [],
            },
        ],
    };

    // 设置图表选项
    chartAge.value.chart.setOption(option);

    // 监听窗口大小变化，调整图表
    window.addEventListener("resize", () => {
        if (chartAge.value.chart) {
            chartAge.value.chart.resize();
        }
    });
};

// 更新宠物年龄分布条形图数据
const updateAgeChart = () => {
    if (!chartAge.value || !chartAge.value.chart || !ageData.value.length) return;

    // 转换数据格式
    const xData = ageData.value.map((item) => item.age_range);
    const yData = ageData.value.map((item) => item.count);

    // 更新图表数据
    chartAge.value.chart.setOption({
        xAxis: {
            data: xData,
        },
        series: [
            {
                data: yData,
            },
        ],
    });
};

onMounted(() => {
    initGenderChart();
    initPublishTypeChart();
    initSpeciesChart();
    initRegionChart();
    initAgeChart();
    getPetAnalysis();
});

// 监听数据变化，更新图表
watch(gerderData, () => {
    updateGenderChart();
});

watch(publishTypeData, () => {
    updatePublishTypeChart();
});

watch(speciesData, () => {
    updateSpeciesChart();
});

watch(regionData, () => {
    updateRegionChart();
});

watch(ageData, () => {
    updateAgeChart();
});
</script>

<style scoped lang="scss">
.pets-data-analysis {
    padding: 20px;

    .el-card {
        margin-bottom: 20px;
    }

    .chart-container {
        width: 100%; // 将宽度调整为100%，以适应容器
        height: 100%;
    }

    .chart-row {
        display: flex;
        flex-wrap: nowrap; // 禁止换行
        justify-content: space-between; // 保持均匀间距
        gap: 20px; // 增加间距（可以适当调整）
    }

    .chart-card {
        flex: 1 0 calc(50% - 10px); // 每个图表卡片占用50%的宽度，并保持间距
        margin-bottom: 20px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        max-width: 48%; // 保证每个卡片不会超过48%的宽度，以适应间距
    }

    .chart-card-3,
    .chart-card-4,
    .chart-card-5 {
        flex: 1 0 calc(33.33% - 20px); // 每个柱状图占据 33.33% 宽度，并确保间距
        margin-bottom: 20px; // 保证底部有间距
        max-width: 33.33%; // 每个图表卡片最大宽度不超过33.33%
        display: flex;
        flex-direction: column;
        justify-content: space-between;
    }
}
</style>
